<template>
  <el-dialog
    v-model="visible"
    :title="isEditMode ? '编辑发布' : '新增发布'"
    width="600px"
    :before-close="handleDialogClose"
  >
    <el-form :model="formData" label-width="80px">
      <el-form-item label="内容">
        <el-input
          v-model="formData.content"
          type="textarea"
          :rows="4"
          placeholder="请输入发布内容"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item label="媒体">
        <div class="media-section">
          <div class="section-header">
            <span class="section-title">添加媒体</span>
            <span class="media-count">{{ selectedImages.length }}/9</span>
          </div>
          <div class="media-grid">
            <div 
              class="media-item" 
              v-for="(image, index) in selectedImages" 
              :key="index"
            >
              <el-image 
                :src="image.url" 
                class="media-image"
                fit="cover"
                :preview-src-list="selectedImages.map(img => img.url)"
                :initial-index="index"
              />
              <div class="remove-overlay" @click="removeImage(index)">
                <span class="remove-icon">×</span>
              </div>
            </div>
            
            <div 
              class="add-media-btn"
              v-if="selectedImages.length < 9"
            >
              <input 
                ref="fileInputRef"
                type="file" 
                accept="image/*" 
                multiple
                @change="handleImageSelect"
                class="file-input"
              />
              <el-button type="primary" link @click="triggerFileInput">
                <span class="add-icon">+</span>
              </el-button>
            </div>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="可见性">
        <el-switch
          v-model="formData.is_public"
          active-text="公开"
          inactive-text="私有"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button 
        type="primary" 
        @click="submitForm"
        :loading="loading"
      >
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Publish } from '@/api/modules/publish'
import { editPublish, createPublish } from '@/api/modules/publish'
import { uploadFile } from '@/api/modules/upload'

const props = defineProps<{
  modelValue: boolean
  publishData: Publish | null
  isEditMode: boolean
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const loading = ref(false)

// 表单数据
const formData = ref({
  content: '',
  is_public: true
})

// 图片相关
const selectedImages = ref<Array<{url: string, file: File, uploadId?: number}>>([])
const fileInputRef = ref<HTMLInputElement | null>(null)

// 监听弹窗打开/关闭
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 弹窗打开时初始化数据
    if (props.isEditMode && props.publishData) {
      formData.value = {
        content: props.publishData.content,
        is_public: props.publishData.is_public !== false
      }
      
      // 初始化已有的图片
      if (props.publishData.images && props.publishData.images.length > 0) {
        selectedImages.value = props.publishData.images.map(img => ({
          url: img.fileurl,
          file: new File([], img.fileurl),
          uploadId: img.upload_id
        }))
      } else {
        selectedImages.value = []
      }
    } else {
      // 新增模式
      formData.value = {
        content: '',
        is_public: true
      }
      selectedImages.value = []
    }
  }
})

// 触发文件选择
const triggerFileInput = () => {
  if (fileInputRef.value) {
    fileInputRef.value.click()
  }
}

// 处理图片选择
const handleImageSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files) {
    const files = Array.from(input.files)
    const remainingSlots = 9 - selectedImages.value.length
    
    // 限制图片数量不超过9张
    const filesToProcess = files.slice(0, remainingSlots)
    
    filesToProcess.forEach(file => {
      const url = URL.createObjectURL(file)
      selectedImages.value.push({
        url,
        file
      })
    })
    
    // 清空input的value，确保下次选择同一文件也能触发change事件
    input.value = ''
  }
}

// 移除图片
const removeImage = (index: number) => {
  selectedImages.value.splice(index, 1)
}

// 上传图片
const uploadImages = async () => {
  const imageIds: number[] = []
  
  for (const image of selectedImages.value) {
    // 如果图片已经有uploadId，说明是已存在的图片，不需要重新上传
    if (image.uploadId) {
      imageIds.push(image.uploadId)
      continue
    }
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('file', image.file)
    
    try {
      const response = await uploadFile(formData)
      if (response.data && response.data.upload_id) {
        imageIds.push(response.data.upload_id)
      }
    } catch (error) {
      console.error('图片上传失败:', error)
      throw error
    }
  }
  
  return imageIds
}

// 提交表单
const submitForm = async () => {
  loading.value = true
  try {
    // 上传图片并获取图片ID
    const imageIds = await uploadImages()
    
    if (props.isEditMode && props.publishData) {
      // 编辑发布
      await editPublish({
        publish_id: props.publishData.publish_id!,
        content: formData.value.content,
        is_public: formData.value.is_public,
        image_ids: imageIds
      })
      ElMessage.success('编辑成功')
    } else {
      // 新增发布
      await createPublish({
        content: formData.value.content,
        is_public: formData.value.is_public,
        image_ids: imageIds
      })
      ElMessage.success('新增成功')
    }
    
    closeDialog()
    emit('success')
  } catch (error) {
    console.error('保存发布失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理对话框关闭
const handleDialogClose = (done: () => void) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的内容将会丢失')
    .then(() => {
      done();
    })
    .catch(() => {
      // 取消关闭
    });
};

// 关闭弹窗
const closeDialog = () => {
  visible.value = false
}
</script>

<style scoped>
/* 媒体选择区域样式 */
.media-section {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #2c3e50;
}

.media-count {
  font-size: 12px;
  color: #999;
}

.media-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.media-item {
  position: relative;
  width: 100%;
  aspect-ratio: 1/1;
  border-radius: 6px;
  overflow: hidden;
}

.media-image {
  width: 100%;
  height: 100%;
}

.remove-overlay {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.media-item:hover .remove-overlay {
  opacity: 1;
}

.remove-icon {
  color: #ffffff;
  font-size: 24px;
  font-weight: bold;
}

.add-media-btn {
  width: 100%;
  aspect-ratio: 1/1;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.add-media-btn:hover {
  border-color: #409eff;
  background-color: #f8faff;
}

.file-input {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}

.add-icon {
  font-size: 30px;
  color: #999;
}

.upload-component {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
</style>